﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Umbraco.Forms.Data.Storage;
using Umbraco.Forms.Core.Services;
using Umbraco.Forms.Core;


namespace ContourStrikesAgain.WorkflowTypes
{
    public class EnergyQuizScoreCalculator : Umbraco.Forms.Core.WorkflowType
    {
        [Umbraco.Forms.Core.Attributes.Setting("Score mappings", 
            description = "Setup how much each answer scores",
            control = "ContourStrikesAgain.FieldSettingTypes.ScoreMapper",
            assembly = "ContourStrikesAgain")]
        public string scoremappings { get; set; }

        [Umbraco.Forms.Core.Attributes.Setting("Field to update", 
            description = "Field that will be populated with the score", 
            control = "Umbraco.Forms.Core.FieldSetting.FieldPicker")]
        public string field { get; set; }

        [Umbraco.Forms.Core.Attributes.Setting("Session key to set", 
            description = "If supplied a session variable will be set", 
            control = "Umbraco.Forms.Core.FieldSetting.TextField")]
        public string sessionkey { get; set; }

        public EnergyQuizScoreCalculator()
        {
            this.Name = "Score Calculator";
            this.Id = new Guid("B3642DEA-1EBE-4552-A81D-49B8D91564B8");
            this.Description = "Calculates a score based on the questions/correct answers";
        }


        public override List<Exception> ValidateSettings()
        {
            List<Exception> exceptions = new List<Exception>();
            return exceptions;
        }


        public override Umbraco.Forms.Core.Enums.WorkflowExecutionStatus Execute(Record record, RecordEventArgs e)
        {
            //calc score
            int score = 0;

            Dictionary<string, int> scores = new Dictionary<string, int>();

            foreach (string mapping in scoremappings.Split(';'))
            {
                if (!string.IsNullOrEmpty(mapping) && mapping.Split(',').Length > 0)
                {
                    int weight = 0;
                    scores.Add(mapping.Split(',')[0], int.TryParse(mapping.Split(',')[1], out weight) ? weight : 0);
                }
            }

            foreach (RecordField rf in record.RecordFields.Values)
            {
                if (rf.Values.Count > 0 && scores.ContainsKey(rf.Values[0].ToString()))
                    score += scores[rf.Values[0].ToString()];
            }

            //set score
            foreach (RecordField rf in record.RecordFields.Values)
            {
                if (rf.Field.Id == new Guid(field))
                {
                    rf.Values.Clear();
                    rf.Values.Add(score);
                    break;
                }
            }

            if (!string.IsNullOrEmpty(sessionkey))
                HttpContext.Current.Session[sessionkey] = score.ToString();

            FormStorage fs = new FormStorage();
            Form f = fs.GetForm(record.Form);
            RecordStorage rs = new RecordStorage();
            rs.UpdateRecord(record, f);
            rs.UpdateRecordXml(record, f);

            fs.Dispose();
            rs.Dispose();

            return Umbraco.Forms.Core.Enums.WorkflowExecutionStatus.Completed;

        }
    }
}